<?php
declare (strict_types=1);

namespace app\platform\business;

use app\common\model\Merchant as MerchantModel;
use app\platform\model\Enterprise as EnterpriseModel;
use app\platform\model\MerchantRoleRelation as MerchantRoleRelationModel;
use app\platform\model\Role as RoleModel;

class Merchant extends PlatformBase
{
    private $_merchantObj = null;
    private const CONFIG_MERCHANT_USER_SESSION_CODE = 'merchant.session_merchant'; // 商户用户 session key 配置 code
    private const CONFIG_STATUS_NORMAL_CODE         = 'status.mysql.table_normal'; // 正常状态配置 code

    public function __construct()
    {
        $this->_merchantObj = new MerchantModel();
    }

    public function login(array $data): bool
    {
        $merchant = $this->getUserByPhoneNumber($data['username']);
        if (!$merchant) {
            return false;
        }

        // 判断密码是否正确
        if ($merchant['password'] != md5($data['password'])) {
            return false;
        }

        $merchantRoleRelationObj  = new MerchantRoleRelationModel();
        $merchantRoleRelations    = $merchantRoleRelationObj->getAllMerchantRoleRelation(['merchant_id' => $merchant['id']]);
        $curMerchantRoleRelations = $merchantRoleRelations->toArray();
        $roleIds                  = [];
        foreach ($curMerchantRoleRelations as $curMerchantRoleRelation) {
            $roleIds[] = $curMerchantRoleRelation['role_id'];
        }

        $merchant['supper']  = $merchant['enterprise_id'] == 0 ? 1 : 0; // 企业ID等于0，表示可以访问任何的站点
        $merchant["roleIds"] = is_null($roleIds) ? [] : $roleIds;

        // 记录 session
        session(config(self::CONFIG_MERCHANT_USER_SESSION_CODE), $merchant);

        return true;
    }

    public function getUserByPhoneNumber(string $name): array
    {
        try {
            $merchant = $this->_merchantObj->findUser(['cellphone' => $name], ['username' => $name]);
        } catch (\Exception $e) {
            // todo 记录错误日志
        }

        if (empty($merchant) || $merchant->status != self::_IS_ENABLE_STATUS) {
            return [];
        }

        return $merchant->toArray();
    }

    public function logout()
    {
        session(config(self::CONFIG_MERCHANT_USER_SESSION_CODE), null);
    }

    public function getMerchantUserFromSession()
    {
        return session(config(self::CONFIG_MERCHANT_USER_SESSION_CODE));
    }

    public function getMerchantList(int $page = 1, int $limit = 10, array $where = []): array
    {
        $rows  = null;
        $count = 0;

        $merchantRoleRelationObj = new MerchantRoleRelationModel();
        $roleObj                 = new RoleModel();
        $enterpriseObj           = new EnterpriseModel();

        try {
            $count = $this->_merchantObj->getMerchantCount($where);

            $merchants = $this->_merchantObj->getMerchantList($page, $limit, $where);
            $rows      = $merchants ? $merchants->toArray() : [];

            foreach ($rows as $key => $row) {
                // 商户拥有角色
                $merchantRoleRelations    = $merchantRoleRelationObj->getAllMerchantRoleRelation(['merchant_id' => $row['id']]);
                $curMerchantRoleRelations = $merchantRoleRelations->toArray();

                $roleIds = [];
                foreach ($curMerchantRoleRelations as $curMerchantRoleRelation) {
                    $roleIds[] = $curMerchantRoleRelation['role_id'];
                }

                $roles     = $roleObj->getAllRole([["id", 'in', $roleIds]]);
                $curRoles  = $roles->toArray();
                $roleNames = [];
                foreach ($curRoles as $curRole) {
                    $roleNames[] = $curRole['name'];
                }
                $rows[$key]['role_name'] = join(', ', $roleNames);


                // 商户所属企业
                $rows[$key]['enterprise_name'] = '--';
                if ($row['enterprise_id']) {
                    $enterprise                    = $enterpriseObj->findEnterpriseById($row['enterprise_id']);
                    $rows[$key]['enterprise_name'] = empty($enterprise) ? '--' : $enterprise['name'];
                }
            }

        } catch (\Exception $e) {
            logErr('读取商户列表失败', sprintf('method:%s,err:%s', __METHOD__, $e->getMessage()));
        }

        return ['rows' => $rows, 'count' => $count];
    }

    public function addMerchant(array $data, string $roleId): array
    {
        unset($data['confirm_password']);
        try {
            return [self::_RESULT => $this->_merchantObj->addMerchant($data, $roleId), self::_MESSAGE => self::_ADD_SUCCESS_MESSAGE];
        } catch (\Exception $e) {
            logErr('添加商户失败', sprintf('method:%s,err:%s', __METHOD__, $e->getMessage()));
        }

        return [self::_RESULT => false, self::_MESSAGE => self::_SYSTEM_ERROR_MESSAGE];
    }

    public function findMerchantById(int $id): array
    {
        $row           = [];
        $relationRoles = [];
        $merchant      = null;
        try {
            $merchant                = $this->_merchantObj->findMerchantById($id);
            $merchantRoleRelationObj = new MerchantRoleRelationModel();
            $relationRoles           = $merchantRoleRelationObj->getAllMerchantRoleRelation(['merchant_id' => $id])->toArray();

        } catch (\Exception $e) {
            logErr('通过主键读取商户详细信息失败', sprintf('method:%s,err:%s', __METHOD__, $e->getMessage()));
        }

        if (empty($merchant)) {
            return [];
        }

        $row      = $merchant->toArray();
        $rolesIds = [];
        foreach ($relationRoles as $relationRole) {
            $rolesIds[] = $relationRole['role_id'];
        }

        $row['role_ids'] = json_encode($rolesIds, JSON_UNESCAPED_UNICODE);

        return $row;
    }

    public function updateMerchant(int $id, array $data, string $roleId = ''): array
    {
        if (!empty($data['password'])) {
            $data['password'] = md5($data['password']);
            unset($data['confirm_password']);
        }

        try {
            return [self::_RESULT => $this->_merchantObj->updateMerchant($id, $data, $roleId), self::_MESSAGE => self::_UPDATE_SUCCESS_MESSAGE];
        } catch (\Exception $e) {
            logErr('通过主键更新商户失败', sprintf('method:%s,err:%s', __METHOD__, $e->getMessage()));
        }

        return [self::_RESULT => false, self::_MESSAGE => self::_SYSTEM_ERROR_MESSAGE];

    }

    public function deleteMerchant(int $id): array
    {
        try {
            return [self::_RESULT => $this->_merchantObj->deleteMerchant($id), self::_MESSAGE => self::_DELETE_SUCCESS_MESSAGE];
        } catch (\Exception $e) {
            logErr('通过主键删除商户失败', sprintf('method:%s,err:%s', __METHOD__, $e->getMessage()));
        }

        return [self::_RESULT => false, self::_MESSAGE => self::_SYSTEM_ERROR_MESSAGE];
    }
}
